﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MaxLeaf.Platform.DataContract;
using CommonsLib.DB;
using MaxLeaf.Platform.DALImplementation;
using MaxLeaf.Platform.Functions;
using CommonsLib.Utility;
using MaxLeaf.Platform.Commons;
using System.Data.Common;
using System.Data.SqlClient;
using System.Transactions;
using System.Data;

namespace MaxLeaf.Platform.BLLImplementation
{
    public class goods_UserKeywordsBLL : BaseBLL
    {
          
        internal List<string> GetUserKeywords( int intCompanyID, string strStKeywords, int intConut)
        {
            List<string> lst = new List<string>();

            using (TransactionScope tx = DataFunc.CreateTransactionScope())
            {
                
                using (DBAccess dbcon  = new DBAccess(DataFunc.GetConnectionInfo(MaxLeaf.Platform.Commons.Const.DB_SCPBase)))
                {
                    string strKeywordsTemplate=string.Empty;
                    int intIndex=0;
                    int intLen = 0;
                    GetKeywordsTemplate(strStKeywords, ref strKeywordsTemplate, ref intIndex, ref intLen);

                    goods_UserKeywordsDAL dal = new goods_UserKeywordsDAL();

                    dal.GetMaxUserKeywordsIndex(dbcon, intCompanyID, ref strKeywordsTemplate, ref intIndex,ref intLen);

                    for (int i = 0; i < intConut; i++)
                    {
                        dal.GetUserKeywords(dbcon, intCompanyID, ref strKeywordsTemplate, ref intIndex, ref intLen);
                        lst.Add(string.Format("{0}{1}", strKeywordsTemplate, BaseFunc.FormatWithZero( intIndex.ToString(),intLen)));

                        intIndex++;
                    }
                }

             
            }

            return lst;
             
        }

        private void GetKeywordsTemplate(string strStKeywords, ref string strKeywordsTemplate, ref int intIndex, ref int intLen)
        {
            int i = strStKeywords.Length-1;
            while(true)
            {
                if(i<0) break;
                string tmp = CvtFunc.ToSubstring(strStKeywords, i, 1);
                if (tmp.CompareTo( "0")>=0 && tmp.CompareTo( "9")<=0) { i--; }
                else
                {
                    break;
                }
            }
            if (i ==strStKeywords.Length - 1)
            {
                strKeywordsTemplate =  strStKeywords ;
                intIndex =1;
                intLen = 1;
            }
            else if (i <0)
            {
                strKeywordsTemplate = "";
                intIndex = CvtFunc.ToInt(strStKeywords);
                intLen = strStKeywords.Length;
            }
            else
            {
                strKeywordsTemplate = CvtFunc.ToLeftString(strStKeywords, i + 1);
                intIndex = CvtFunc.ToInt(CvtFunc.ToSubstring(strStKeywords, i + 1));
                intLen = strStKeywords.Length - i-1;
            }
        }

        public override object Add(object model)
        {

            using (System.Transactions.TransactionScope ts = DataFunc.CreateTransactionScope())
            {
                
                object obj = base.Add(model);

                using (DBAccess dbcon = new DBAccess(DataFunc.GetConnectionInfo(Const.DB_SCPBase)))
                {
                    goods_UserKeywordsDataModel data = (goods_UserKeywordsDataModel)model;
                    AddChild(dbcon, data);


                }

                ts.Complete();

                return obj;
            }
        }

        public override object Update(object model)
        {

            using (System.Transactions.TransactionScope ts = DataFunc.CreateTransactionScope())
            {
                using (DBAccess dbcon = new DBAccess(DataFunc.GetConnectionInfo(Const.DB_SCPBase)))
                {
                    goods_UserKeywordsDataModel data = (goods_UserKeywordsDataModel)model;
                    goods_UserKeywordsDataModel olddata = (goods_UserKeywordsDataModel)Select(new goods_UserKeywordsDataModel(), data.Key);
                    if (olddata == null || data.CompanyID != olddata.CompanyID)
                    {
                        DeleteChild(dbcon, olddata);
                        AddChild(dbcon, data);
                    }
                    else
                    {
                        UpdateChild(dbcon, olddata, data);
                    }
                    

                }
                object obj = base.Update(model);
                ts.Complete();

                return obj;
            }
        }

        private void UpdateChild(DBAccess dbcon, goods_UserKeywordsDataModel oldparentData, goods_UserKeywordsDataModel parentData)
        {
            DataTable dt = GetChildCompany(dbcon, oldparentData.Key);
            foreach (DataRow dr in dt.Rows)
            {
                bool blnUpdate = false;
                foreach (goods_UserKeywordsDataModel child in SelectByCond(new goods_UserKeywordsDataModel()
                    , new List<AddInfo>() { 
                                new AddInfo{ Name= AddInfoType.Cond ,Value= new List<Cond>() { 
                                        new Cond { PropName ="ItemID", Compare = CompareType.Equal, Value = oldparentData.ItemID }
                                        ,new Cond { PropName ="CompanyID", Compare = CompareType.Equal, Value =CvtFunc.ToInt(dr["CompanyID"]) }
                                    }
                                } 
                            }
                ).Data)
                {
                    blnUpdate = true;

                    child.ItemID = parentData.ItemID;
                    child.Keywords = parentData.Keywords;

                    base.Update(child);
                }
                if (!blnUpdate)
                {
                    AddChild(dbcon, parentData);
                }
            }
        }

        private void AddChild(DBAccess dbcon, goods_UserKeywordsDataModel parentData)
        {
            DataTable dt = GetChildCompany(dbcon, parentData.Key);
            foreach (DataRow dr in dt.Rows)
            {
                goods_UserKeywordsDataModel child = new goods_UserKeywordsDataModel { 

                };
                child.CompanyID = CvtFunc.ToInt(dr["CompanyID"]);
                child.ItemID = parentData.ItemID;
                child.Keywords = parentData.Keywords;
                base.Add(child);

            }
        }

        public override bool Delete(object model)
        {

            using (System.Transactions.TransactionScope ts = DataFunc.CreateTransactionScope())
            {
                using (DBAccess dbcon = new DBAccess(DataFunc.GetConnectionInfo(Const.DB_SCPBase)))
                {
                    DeleteChild(dbcon, (goods_UserKeywordsDataModel)model);
                }
                bool blnRT = base.Delete(model);
                ts.Complete();

                return blnRT;
            }
        }

        private void DeleteChild(DBAccess dbcon, goods_UserKeywordsDataModel parentData)
        {
            DataTable dt = GetChildCompany(dbcon, parentData.Key);
            foreach (DataRow dr in dt.Rows)
            {
                foreach (goods_UserKeywordsDataModel child in SelectByCond(new goods_UserKeywordsDataModel()
                    , new List<AddInfo>() { 
                                new AddInfo{ Name= AddInfoType.Cond ,Value= new List<Cond>() { 
                                        new Cond { PropName ="ItemID", Compare = CompareType.Equal, Value = parentData.ItemID }
                                        ,new Cond { PropName ="CompanyID", Compare = CompareType.Equal, Value =CvtFunc.ToInt(dr["CompanyID"]) }
                                    }
                                } 
                            }
                ).Data)
                {
                    base.Delete(child);
                }
            }
        }

        private DataTable GetChildCompany(DBAccess dbcon, int intKey)
        {
            string strSql = @"select distinct a.CompanyID from mCompany a  inner join  goods_UserKeywords b  
                        on  dbo.F_GetParentCompanyID(a.CompanyID)=b.company_id and b.company_id<>0 
                        where b.usegoods_id=@Key";
            DataTable dt = dbcon.GetDataTable(strSql, new SqlParameter[]{
                        new SqlParameter("@Key",intKey.ToString())                        
                    });
            return dt;
        }

    }
}
